﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection.Metadata;
using ClassLibrary;
using ClassLibrary.Service;
using MainForm;

namespace Forms
{
    public partial class ModifyBasicInformationForm : UIForm
    {
        User user;
        Image userImage;
        public ModifyBasicInformationForm(User user, Image userImage)
        {
            InitializeComponent();
            this.user = user;
            this.userImage = userImage;
            nameTextBox.Text = user.UserName;
            idLabel.Text = user.UserID;
            idCardLabel.Text = user.UserIdentityCard;
            teleTextBox.Text = user.UserTele;
            addressTextBox.Text = user.UserAddress;
            profilePictureBox.Image = userImage;
            Color userColor = MainForm.MainForm.userColor;
            UIStyles.InitColorful(userColor, Color.White);
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            try
            {
                User newUser = new User(user.UserID, nameTextBox.Text, user.UserPassword, teleTextBox.Text, user.UserIdentityCard,
                    user.UseIDCardPhoto, new Blob(), addressTextBox.Text);
                newUser.UserColor = MainForm.MainForm.userColor.ToArgb().ToString();
                using (var ctx = new SystemContext())
                {
                    ctx.Entry(user).State = System.Data.Entity.EntityState.Deleted;
                    ctx.Entry(newUser).State = System.Data.Entity.EntityState.Added;
                    ctx.SaveChanges();
                }
                UIMessageBox.Show("成功修改信息");
                this.Close();
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message);
            }
        }

        private void profilePictureBox_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string imagePath = openFileDialog.FileName;
                profilePictureBox.Image = Image.FromFile(imagePath);
                string uploaderID = user.UserID;
                ImageService imageService = new ImageService();
                imageService.DeleteImage(user.UserID, null, "T_profile");
                ImageService.SaveImageToDatabaseByPath(imagePath, uploaderID, "T_profile");
            }
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ModifyBasicInformationForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            
        }
    }
}
